package com.bit.lotterySystem.common.utils;

import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class AliYuanSMSUtil {
    private static final Logger log = LoggerFactory.getLogger(AliYuanSMSUtil.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${sms.access-key-id}")
    private String accessKeyId;
    @Value("${sms.access-key-secret}")
    private String accessKeySecret;

    // 创建客户端
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dypnsapi.aliyuncs.com"; // 号码认证服务的 Endpoint
        return new Client(config);
    }

    /**
     * 生成6位随机验证码
     */
    public String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     *生成length位随机验证码
     */
    public String generateCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送验证码到指定手机号
     * @param phone 接收验证码的手机号
     * @return 发送结果
     */
    public void sendCode(String phone, String code, Long timeout) {
        try {
            SendSmsVerifyCodeRequest request = new SendSmsVerifyCodeRequest()
                    .setPhoneNumber(phone)
                    .setSignName("速通互联验证码")
                    .setTemplateCode("100001")
                    .setTemplateParam("{\"code\":\"" + code + "\",\"min\":\""+timeout+"\"}");

            SendSmsVerifyCodeResponse response = createClient().sendSmsVerifyCode(request);

            if ("OK".equals(response.getBody().getCode())) {
                log.info("向{}发送验证码成功，请注意查收",phone);
            } else {
                log.error("向{}发送失败：{}",phone,response.getBody().getMessage());
            }

        } catch (TeaException e) {
            log.error("向{}发送失败：{}",phone,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
           log.error("发送失败：系统异常");
        }
    }

    /**
     * 验证用户输入的验证码是否正确
     */
//    public boolean verifyCode(String phone, String inputCode) {
//        if (!phone.matches("^1[3-9]\\d{9}$") || !StringUtils.hasText(inputCode)) {
//            return false;
//        }
//
//        String redisCode = stringRedisTemplate.opsForValue().get("sms:code:" + phone);
//
//        if (inputCode.equals(redisCode)) {
//            stringRedisTemplate.delete("sms:code:" + phone);
//            return true;
//        }
//
//        return false;
//    }
}